package org.dolphin.entity.security;

import java.io.Serializable;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
import org.dolphin.base.constant.DatabaseAttribute;
import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode;
import org.hibernate.annotations.ForeignKey;
import org.hibernate.annotations.GenericGenerator;
import org.springframework.util.ObjectUtils;

@Entity
@Table(name = "XS_URL", uniqueConstraints = {@UniqueConstraint(columnNames = {"URL"}, name = "UQ_XS_URL_URL")})
public class Url implements Serializable {
  private static final long serialVersionUID = 7658356829872764574L;
  private String id;
  private String url;
  private List<AccessControl> accessControls;

  @Override
  public boolean equals(Object obj) {
    if (obj == this) {
      return true;
    } else if (obj instanceof Url) {
      Url oth = (Url) obj;
      return ObjectUtils.nullSafeEquals(getId(), oth.getId());
    }
    return false;
  }

  @ManyToMany(fetch = FetchType.EAGER)
  @JoinTable(name = "XS_ACCESS_CONTROL_URL", joinColumns = @JoinColumn(name = "URL_ID"), inverseJoinColumns = @JoinColumn(name = "ACCESS_CONTROL_ID"), uniqueConstraints = {@UniqueConstraint(columnNames = {
      "URL_ID", "ACCESS_CONTROL_ID"}, name = "UQ_XS_ACCESS_CONTROL_URL_ACCESS_CONTROL_ID")})
  @ForeignKey(name = "FK_XS_ACCESS_CONTROL_URL_URL", inverseName = "FK_XS_ACCESS_CONTROL_URL_ACCESS_CONTROL")
  @Fetch(FetchMode.SUBSELECT)
  public List<AccessControl> getAccessControls() {
    return accessControls;
  }

  @Id
  @GeneratedValue(generator = "uuid2")
  @GenericGenerator(name = "uuid2", strategy = "org.dolphin.base.id.generator.CustomUUIDGenerator")
  @Column(name = "ID", nullable = false, length = DatabaseAttribute.ID_LENGTH)
  public String getId() {
    return id;
  }

  @Column(name = "URL", nullable = false, length = 100)
  public String getUrl() {
    return url;
  }

  @Override
  public int hashCode() {
    int hash = ObjectUtils.nullSafeHashCode(getId());
    return hash;
  }

  public void setAccessControls(List<AccessControl> accessControls) {
    this.accessControls = accessControls;
  }

  public void setId(String id) {
    this.id = id;
  }

  public void setUrl(String url) {
    this.url = url;
  }

  @Override
  public String toString() {
    StringBuilder builder = new StringBuilder();
    builder.append(getUrl());
    return builder.toString();
  }
}
